<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form
        :model="queryParams"
        ref="queryFormRef"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
    >
      <el-form-item label="医院名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入医院名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮行 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
        >
          删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格展示 -->
    <el-table v-loading="loading" :data="hospitalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
<!--      <el-table-column label="医院id" align="center" prop="id"/>-->
      <el-table-column label="医院id" align="center" width="100" type="index"/>
      <el-table-column label="医院图片" align="center" prop="imgurl">
        <template #default="scope">
          <el-image
              :src="scope.row.imgurl"
              style="width: 100px; height: 100px; border-radius: 50%"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
            <template #placeholder>
              <div class="image-slot">
                <el-icon><Loading /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="医院名称" align="center" prop="name"/>
      <el-table-column label="医院所属地址" align="center" prop="addressName"/>
      <el-table-column label="医院所属医生数量" align="center" prop="doctorsNum"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
          >
            修改
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleShowDep(scope.row)"
          >
            详情科室
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        v-if="total > 0"
        v-model:current-page="queryParams.currentPage"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[1, 3, 10, 20]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="850px" append-to-body :close-on-click-modal="false" :before-close="handleDialogClose">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <div class="avatar-section">
          <el-form-item prop="imgurl">
            <el-upload
                class="avatar-uploader"
                action="/api/hospital/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                accept="image/jpeg,image/png,image/jpg"
            >
              <el-image
                  v-if="form.imgurl"
                  :src="form.imgurl"
                  class="avatar"
                  fit="cover"
                  style="width: 100px; height: 100px; border-radius: 50%"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
                <template #placeholder>
                  <div class="image-slot">
                    <el-icon><Loading /></el-icon>
                  </div>
                </template>
              </el-image>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </div>
        <el-form-item label="医院名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入医院名称"/>
        </el-form-item>
        <el-form-item label="所属地址">
          <el-form-item prop="provinceId">
            <el-select
                v-model="form.provinceId"
                placeholder="请选择省份"
                size="large"
                style="width: 240px"
                @change="handleProvinceChange"
            >
              <el-option
                  v-for="item in provincesOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="cityId">
            <el-select
                v-model="form.cityId"
                placeholder="请选择城市"
                style="width: 240px"
                @change="getDistrictsForCity"
            >
              <el-option
                  v-for="item in cityList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="districtId">
            <el-select
                v-model="form.districtId"
                placeholder="请选择区域"
                size="small"
                @change="handleDistrictChange"
                style="width: 240px"
            >
              <el-option
                  v-for="item in districtList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item label="详细地址" prop="address.detailedAddress">
          <el-input 
            v-model="form.address.detailedAddress" 
            placeholder="请输入详细地址"
            @blur="validateDetailedAddress"
          />
        </el-form-item>
        <el-form-item label="地图选点">
          <div style="width: 100%; height: 400px;">
            <Map 
              ref="mapRef"
              :address="form.address"
              @update-address="handleMapAddressUpdate"
            />
          </div>
        </el-form-item>

        <el-form-item label="医生数量" prop="doctorsNum">
          <el-input 
              v-model="form.doctorsNum" 
              placeholder="请输入医院所属医生数量"
              :disabled="true"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            type="primary" 
            @click="debouncedSubmitForm" 
            :loading="submitLoading"
            :disabled="submitLoading">
            确 定
          </el-button>
          <el-button @click="cancel" :disabled="submitLoading">
            取 消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import Map from "./Map.vue";
import {ref, onMounted} from 'vue';
import {
  listHospital,
  getHospital,
  addHospital,
  updateHospital,
  delHospital,
} from '../../api/hospital/hospital.js';
import axios from 'axios';
import router from "../../router/index.js";
import {ElMessage, ElMessageBox} from "element-plus";

// 添加防抖函数
function debounce(fn, delay = 300) {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay);
  };
}

// 遮罩层
const loading = ref(true);
// 提交按钮加载状态
const submitLoading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 医院列表数据
const hospitalList = ref([]);
// 弹出层标题
const title = ref('');
// 是否显示弹出层
const open = ref(false);

// 查询参数
const queryParams = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  name: null,
  queryString: null,
});

// 选择查询条件
const selectQueryCondition = () => {
  if (queryParams.value.name) {
    queryParams.value.queryString = queryParams.value.name;
  } else {
    queryParams.value.queryString = null;
  }
};

// 表单参数
const form = ref({
  id: null,
  imgurl: null,
  name: null,
  address: {
    province: null,
    city: null,
    district: null,
    detailedAddress: null,
    provinceId: null,
    cityId: null,
    districtId: null,
  },
  provinceId: null,
  cityId: null,
  districtId: null,
  detailedAddress: null,
  doctorsNum: 0,
  longitude: null,
  latitude: null
});

// 表单校验规则
const rules = ref({
  imgurl: [
    { required: true, message: '请上传医院图片', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入医院名称', trigger: 'blur' }
  ],
  provinceId: [
    { required: true, message: '请选择省份', trigger: 'change' }
  ],
  cityId: [
    { required: true, message: '请选择城市', trigger: 'change' }
  ],
  districtId: [
    { required: true, message: '请选择区域', trigger: 'change' }
  ],
  'address.detailedAddress': [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  longitude: [
    { required: true, message: '请在地图上选择位置', trigger: 'change' }
  ],
  latitude: [
    { required: true, message: '请在地图上选择位置', trigger: 'change' }
  ]
});

// 表单引用
const formRef = ref(null);
const queryFormRef = ref(null);

// 获取列表数据
const getList = async () => {
  selectQueryCondition();
  loading.value = true;
  try {
    const res = await listHospital(queryParams.value);
    console.log('获取到的列表数据:', res);
    hospitalList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('获取列表数据失败:', error);
    ElMessage.error('获取列表数据失败');
  } finally {
    loading.value = false;
  }
};

/**
 * 分页
 */
// 添加分页处理方法
// 页面大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  getList();
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.currentPage = val;
  getList();
}
const imageUrl = ref('')

// 头像上传成功
const handleAvatarSuccess = (res, uploadFile) => {
  if (res.code === 200) {
    imageUrl.value = URL.createObjectURL(uploadFile.raw);
    form.value.imgurl = res.data;
    // 手动触发表单验证
    formRef.value?.validateField('imgurl');
  } else {
    ElMessage.error(res.msg || '上传失败');
  }
};
//验证的函数
const beforeAvatarUpload = (rawFile) => {
  const isImage = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png' || rawFile.type === 'image/jpg';
  if (!isImage) {
    ElMessage.error('Avatar picture must be in JPG, PNG, or JPEG format!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size cannot exceed 2MB!');
    return false;
  }
  return true;
}
// 取消按钮操作
const cancel = () => {
  // 重置表单
  formRef.value?.resetFields();
  // 重置数据
  reset();
  // 重置地图
  mapRef.value?.resetMap();
  // 关闭对话框
  open.value = false;
  // 确保提交按钮状态重置
  submitLoading.value = false;
};

// 表单重置
const reset = () => {
  form.value = {
    id: null,
    imgurl: null,
    name: null,
    address: {
      province: null,
      city: null,
      district: null,
      detailedAddress: null,
      provinceId: null,
      cityId: null,
      districtId: null,
    },
    provinceId: null,
    cityId: null,
    districtId: null,
    doctorsNum: 0,
    longitude: null,
    latitude: null
  };
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.value.currentPage = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields();
  }
  handleQuery();
};

// 多选框选中数据处理
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 省的选项数据数组
const provincesOptions = ref([]);
const cityList = ref([]);
const districtList = ref([]);

function findProvinces() {
  axios({
    url: '/province/findProvinces',
    method: 'get',
  }).then((res) => {
    if (res.data.code === 200) {
      provincesOptions.value = res.data.data;
      console.log('省份数据:', provincesOptions.value);
    } else {
      ElMessage.error('获取省份数据失败');
    }
  }).catch((error) => {
    console.error('获取省份数据失败:', error);
    ElMessage.error('获取省份数据失败');
  });
}

const mapRef = ref(null);

function handleProvinceChange(provinceId) {
  console.log('选择省份:', provinceId);
  
  // 清空城市和区域数据
  cityList.value = [];
  districtList.value = [];
  form.value.cityId = null;
  form.value.districtId = null;

  // 设置省份信息
  const selectedProvince = provincesOptions.value.find(
    (province) => province.id === provinceId
  );

  if (selectedProvince) {
    // 更新所有相关的省份信息
    form.value.provinceId = provinceId;
    
    // 更新地址对象，保持现有结构
    form.value.address = {
      ...form.value.address,
      province: selectedProvince.name,
      city: null,
      district: null,
      provinceId: provinceId,
      cityId: null,
      districtId: null
    };

    console.log('正在定位到省份:', selectedProvince.name);

    // 获取城市列表
    axios({
      url: '/city/findCity',
      method: 'get',
      params: {provinceId},
    }).then((res) => {
      if (res.data.code === 200) {
        cityList.value = res.data.data;
        console.log('获取到的城市列表:', cityList.value);
      } else {
        ElMessage.error('获取城市数据失败');
      }
    }).catch((error) => {
      console.error('获取城市数据失败:', error);
      ElMessage.error('获取城市数据失败');
    });
  }
}

function getDistrictsForCity(cityId) {
  console.log('选择城市:', cityId);
  
  // 清空区域数据
  districtList.value = [];
  form.value.districtId = null;

  // 设置城市信息
  const selectedCity = cityList.value.find(
    (city) => city.id === cityId
  );

  if (selectedCity) {
    form.value.cityId = cityId;
    
    // 更新地址对象，保持现有结构
    form.value.address = {
      ...form.value.address,
      city: selectedCity.name,
      district: null,
      cityId: cityId,
      districtId: null,
      province: form.value.address.province,
      provinceId: form.value.provinceId,
      detailedAddress: form.value.address.detailedAddress
    };

    console.log('正在定位到城市:', selectedCity.name);

    // 获取区域列表
    axios({
      url: '/district/findDistrict',
      method: 'get',
      params: {cityId},
    }).then((res) => {
      if (res.data.code === 200) {
        districtList.value = res.data.data;
        console.log('获取到的区域列表:', districtList.value);
      } else {
        ElMessage.error('获取区域数据失败');
      }
    }).catch((error) => {
      console.error('获取区域数据失败:', error);
      ElMessage.error('获取区域数据失败');
    });
  }
}

function handleDistrictChange(districtId) {
  console.log('选择区域:', districtId);
  
  const selectedDistrict = districtList.value.find(
    (district) => district.id === districtId
  );

  if (selectedDistrict) {
    form.value.districtId = districtId;
    
    // 更新地址对象，保持现有结构
    form.value.address = {
      ...form.value.address,
      district: selectedDistrict.name,
      districtId: districtId,
      province: form.value.address.province,
      city: form.value.address.city,
      provinceId: form.value.provinceId,
      cityId: form.value.cityId,
      detailedAddress: form.value.address.detailedAddress
    };

    console.log('正在定位到区域:', selectedDistrict.name);
  }
}

// 添加详细地址变化处理函数
const handleDetailedAddressChange = () => {
  console.log('输入详细地址:', form.value.address.detailedAddress);
  
  if (form.value.address.detailedAddress) {
    // 更新地址对象
    form.value.address = {
      ...form.value.address,
      detailedAddress: form.value.address.detailedAddress
    };
    
    console.log('正在定位到详细地址');
    // 更新地图位置到详细地址
    updateMapLocation();
  }
};

// 添加地图位置变化处理函数
const handleLocationChange = (location) => {
  console.log('地图位置变化:', location);
  // 这里可以处理地图返回的位置信息
};

// 新增按钮操作
const handleAdd = () => {
  // 确保先重置表单再打开对话框
  formRef.value?.resetFields();
  reset();
  // 重置提交状态
  submitLoading.value = false;
  // 设置标题和打开对话框
  title.value = '添加';
  open.value = true;
};

// 修改按钮操作
const handleUpdate = async (row) => {
  // 先重置状态
  formRef.value?.resetFields();
  reset();
  submitLoading.value = false;
  
  const id = row?.id || ids.value[0];
  if (!id) {
    ElMessage.error('未选择有效的医院信息');
    return;
  }

  // 显示加载状态
  loading.value = true;
  
  try {
    // 先加载省份数据
    await findProvinces();
    
    const res = await getHospital(id);
    console.log('获取医院信息响应:', res);

    if (res.code === 200) {
      const hospitalData = res.data;
      form.value = {
        id: hospitalData.id,
        imgurl: hospitalData.imgurl,
        name: hospitalData.name,
        address: hospitalData.address || {
          province: null,
          city: null,
          district: null,
          detailedAddress: null,
          provinceId: null,
          cityId: null,
          districtId: null,
        },
        provinceId: hospitalData.address?.provinceId,
        cityId: hospitalData.address?.cityId,
        districtId: hospitalData.address?.districtId,
        doctorsNum: hospitalData.doctorsNum
      };

      // 如果有省份ID，加载对应的城市列表
      if (form.value.provinceId) {
        // 设置省份名称
        const selectedProvince = provincesOptions.value.find(
          (province) => province.id === form.value.provinceId
        );
        if (selectedProvince) {
          form.value.address.province = selectedProvince.name;
        }

        // 加载城市列表
        try {
          const cityRes = await axios({
            url: '/city/findCity',
            method: 'get',
            params: { provinceId: form.value.provinceId },
          });

          if (cityRes.data.code === 200) {
            cityList.value = cityRes.data.data;

            // 如果有城市ID，加载对应的区域列表
            if (form.value.cityId) {
              // 设置城市名称
              const selectedCity = cityList.value.find(
                (city) => city.id === form.value.cityId
              );
              if (selectedCity) {
                form.value.address.city = selectedCity.name;
              }

              // 加载区域列表
              const districtRes = await axios({
                url: '/district/findDistrict',
                method: 'get',
                params: { cityId: form.value.cityId },
              });

              if (districtRes.data.code === 200) {
                districtList.value = districtRes.data.data;

                // 设置区域名称
                if (form.value.districtId) {
                  const selectedDistrict = districtList.value.find(
                    (district) => district.id === form.value.districtId
                  );
                  if (selectedDistrict) {
                    form.value.address.district = selectedDistrict.name;
                  }
                }
              }
            }
          }
        } catch (error) {
          console.error('加载地址数据失败:', error);
          ElMessage.error('加载地址数据失败');
        }
      }

      title.value = '修改';
      open.value = true;
    } else {
      ElMessage.error(res.msg || '获取医院信息失败');
    }
  } catch (error) {
    console.error('获取医院信息失败:', error);
    ElMessage.error('获取医院信息失败');
  } finally {
    loading.value = false;
  }
};

// 对话框关闭处理函数
const handleDialogClose = (done) => {
  if (submitLoading.value) {
    ElMessage.warning('正在提交数据，请稍后...');
    return;
  }
  
  // 重置表单
  formRef.value?.resetFields();
  // 重置数据
  reset();
  // 重置地图
  mapRef.value?.resetMap();
  // 确保提交按钮状态重置
  submitLoading.value = false;
  
  done();
};

// 提交表单操作
const submitForm = async () => {
  if (formRef.value) {
    try {
      // 防止重复提交
      if (submitLoading.value) {
        return;
      }
      
      // 表单验证
      await formRef.value.validate();
      
      // 获取经纬度信息
      const location = mapRef.value?.getLocation();
      if (!location) {
        ElMessage.error('请在地图上选择位置');
        return;
      }
      
      // 立即设置提交状态为加载中
      submitLoading.value = true;

      // 构建提交的数据
      const submitData = {
        ...form.value,
        addressName: `${form.value.address.province}${form.value.address.city}${form.value.address.district}${form.value.address.detailedAddress}`,
        longitude: location.longitude,
        latitude: location.latitude
      };

      // 克隆一个副本用于提交，避免引用问题
      const submitFormData = JSON.parse(JSON.stringify(submitData));

      const res = form.value.id !== null
        ? await updateHospital(submitFormData)
        : await addHospital(submitFormData);

      console.log('提交响应:', res);
      if (res.code === 200) {
        ElMessage.success(form.value.id !== null ? '修改成功' : '新增成功');
        
        // 先刷新表格数据
        await getList();
        
        // 最后关闭对话框
        open.value = false;
      } else {
        ElMessage.error(res.msg || '操作失败');
      }
    } catch (error) {
      console.error('表单提交失败:', error);
      ElMessage.error('表单提交失败');
    } finally {
      // 延迟重置提交状态，确保按钮禁用效果明显
      setTimeout(() => {
        submitLoading.value = false;
      }, 500);
    }
  }
};

// 使用防抖包装提交函数
const debouncedSubmitForm = debounce(submitForm, 300);

// 删除按钮操作
const handleDelete = (row) => {
  const deleteIds = row?.id || ids.value;
  if (!deleteIds || (Array.isArray(deleteIds) && deleteIds.length === 0)) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }

  ElMessageBox.confirm(
    Array.isArray(deleteIds)
      ? `是否确认删除选中的 ${deleteIds.length} 条数据?`
      : `是否确认删除编号为"${deleteIds}"的数据项？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        const res = await delHospital(deleteIds);
        console.log('删除响应:', res);
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          });
          ids.value = [];
          await getList();
        } else {
          ElMessage.error(res.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除医院信息失败:', error);
        ElMessage.error('删除失败，请稍后重试');
      }
    })
    .catch(() => {
      // 用户点击取消按钮
    });
};

const handleShowDep = async (row) => {
  console.log("row-id："+row.id);
  console.log("row-name："+row.name);
  // router.push("/showDep")
  router.push({
    name: 'showDep',
    params: {
      id: row.id,
      name: row.name
    }
  });
}
// 导出按钮操作
const handleExport = () => {
  const download = (url, params, filename) => {
    console.log('导出请求:', url, params, filename);
  };
  download('system/hospital/export', {
    ...queryParams.value,
  }, `hospital_${new Date().getTime()}.xlsx`);
};

// 添加地图地址更新处理函数
const handleMapAddressUpdate = async (address) => {
  console.log('地图选点更新地址:', address);
  
  try {
    // 先加载省份数据
    await findProvinces();
    
    // 查找并设置省份
    const selectedProvince = provincesOptions.value.find(
      province => province.name === address.province
    );
    
    if (selectedProvince) {
      form.value.provinceId = selectedProvince.id;
      form.value.address.province = selectedProvince.name;
      form.value.address.provinceId = selectedProvince.id;
      
      // 加载城市列表
      const cityRes = await axios({
        url: '/city/findCity',
        method: 'get',
        params: { provinceId: selectedProvince.id },
      });
      
      if (cityRes.data.code === 200) {
        cityList.value = cityRes.data.data;
        
        // 查找并设置城市
        const selectedCity = cityList.value.find(
          city => city.name === address.city
        );
        
        if (selectedCity) {
          form.value.cityId = selectedCity.id;
          form.value.address.city = selectedCity.name;
          form.value.address.cityId = selectedCity.id;
          
          // 加载区域列表
          const districtRes = await axios({
            url: '/district/findDistrict',
            method: 'get',
            params: { cityId: selectedCity.id },
          });
          
          if (districtRes.data.code === 200) {
            districtList.value = districtRes.data.data;
            
            // 查找并设置区域
            const selectedDistrict = districtList.value.find(
              district => district.name === address.district
            );
            
            if (selectedDistrict) {
              form.value.districtId = selectedDistrict.id;
              form.value.address.district = selectedDistrict.name;
              form.value.address.districtId = selectedDistrict.id;
            }
          }
        }
      }
    }
    
    // 设置详细地址
    form.value.address.detailedAddress = address.detailedAddress;
    
  } catch (error) {
    console.error('更新地址信息失败:', error);
    ElMessage.error('更新地址信息失败');
  }
};

// 添加详细地址校验函数
const validateDetailedAddress = async () => {
  if (!form.value.address.detailedAddress) return;
  
  // 检查是否已选择省市区
  if (!form.value.address.province || !form.value.address.city || !form.value.address.district) {
    ElMessage.warning('请先选择省市区');
    form.value.address.detailedAddress = '';
    return;
  }

  // 构建完整地址
  const fullAddress = `${form.value.address.province}${form.value.address.city}${form.value.address.district}${form.value.address.detailedAddress}`;
  
  // 使用地图的地理编码服务验证地址
  try {
    const geocoder = new AMap.Geocoder({
      city: form.value.address.city
    });
    
    const result = await new Promise((resolve, reject) => {
      geocoder.getLocation(fullAddress, (status, result) => {
        if (status === 'complete' && result.geocodes.length) {
          resolve(result.geocodes[0]);
        } else {
          reject(new Error('地址解析失败'));
        }
      });
    });

    // 检查解析出的地址是否在正确的省市区内
    const addressComponent = result.addressComponent;
    
    // 移除"市"、"省"、"自治区"等后缀进行比较
    const normalizeAddress = (addr) => {
      return addr?.replace(/(省|市|自治区|特别行政区|区|县)$/, '') || '';
    };

    const selectedProvince = normalizeAddress(form.value.address.province);
    const selectedCity = normalizeAddress(form.value.address.city);
    const selectedDistrict = normalizeAddress(form.value.address.district);

    const mapProvince = normalizeAddress(addressComponent.province);
    const mapCity = normalizeAddress(addressComponent.city || addressComponent.province);
    const mapDistrict = normalizeAddress(addressComponent.district);

    if (selectedProvince !== mapProvince || 
        selectedCity !== mapCity || 
        selectedDistrict !== mapDistrict) {
      ElMessage.error(`输入的地址不在${form.value.address.province}${form.value.address.city}${form.value.address.district}范围内`);
      form.value.address.detailedAddress = '';
      return;
    }

    // 更新地图位置
    if (mapRef.value) {
      mapRef.value.updateMapFromAddress();
    }

  } catch (error) {
    console.error('地址验证失败:', error);
    ElMessage.error('地址验证失败，请检查输入的地址是否正确');
    form.value.address.detailedAddress = '';
  }
};

onMounted(() => {
  getList();
  findProvinces();
});
</script>
